<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="600px"
    :close-on-click-modal="false"
    :before-close="closeDialog"
  >
    <el-form ref="ruleForm" :model="form" :rules="rules" label-width="60px">
      <el-form-item prop="name" label="名称">
        <el-input
          placeholder="请输入角色名称"
          maxlength="20"
          v-model="form.name"
        ></el-input>
      </el-form-item>

      <el-form-item prop="remark" label="备注">
        <el-input
          placeholder="请输入备注"
          maxlength="20"
          v-model="form.remark"
        ></el-input>
      </el-form-item>

      <div class="dialog-btns">
        <el-button @click="editHandle" type="primary" size="medium">{{
          this.form.id ? "编辑" : "新增"
        }}</el-button>
        <el-button @click="closeDialog" size="medium">取消</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>
  
<script>
import { addRole, updateRole } from "@/api/organization/role";
export default {
  name: "RoleEdit",
  props: {
    formData: {
      type: Object,
    },
    title: {
      type: String,
    },
    dialogVisible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      form: {},
      rules: {
        name: [
          {
            required: true,
            min: 2,
            max: 20,
            message: "名称长度2到8个字",
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    this.form = JSON.parse(JSON.stringify(this.formData));
  },
  methods: {
    editHandle() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let { id, name, remark } = this.form;
          if (id) {
            updateRole({ id, name, remark }).then((res) => {
              this.closeDialog("refresh");
            });
          } else {
            addRole({ name, remark }).then((res) => {
              this.closeDialog("refresh");
            });
          }
        } else {
          return false;
        }
      });
    },
    closeDialog(type) {
      if (type === "refresh") {
        setTimeout(() => {
          this.form = {};
          this.$emit("closeDialog", type === "refresh");
        }, 100);
      } else {
        this.form = {};
        this.$emit("closeDialog", type === "refresh");
      }
    },
  },
  computed: {
    dialogTitle() {
      return (this.formData.id ? "编辑 " : "新增") + this.title;
    },
  },
};
</script>

<style>
</style>